<template>
  <div class="page grey-stage">
    <div class="container add-follow-main">
      <div class="cell textarea-wrapper">
        <div class="case-wrapper">
          <checker v-model="caseValue"
          default-item-class="ad-checker-item"
          selected-item-class="ad-checker-selected"
          >
            <checker-item value="#未接#" class="checker-item-label case-item">#未接#</checker-item>
            <checker-item value="#空号#" class="checker-item-label case-item">#空号#</checker-item>
            <checker-item value="#停机#" class="checker-item-label case-item">#停机#</checker-item>
            <checker-item value="#超龄#" class="checker-item-label case-item">#超龄#</checker-item>
          </checker>
        </div>
        <div class="txtare-block">
          <textarea
          :class="{'weui-cell_warn': $v.follow.clue_desc.$error }"
          placeholder="请输入跟进记录" v-model="follow.clue_desc" ></textarea>
        </div>
        <p class="clue-locaton-desc" v-if="follow.clue_location_desc">
          <i class="location-ico"></i>{{ follow.clue_location_desc }}
        </p>
        <div class="cell image-contr">
          <div class="image-item" v-for="(img, index) in follow.imgs" :key="index">
            <i class="delete" @click="deleteImage(img)">x</i>
            <img :src="img.url" />
          </div>
          <div class="previewed-image image-item">
            <span class="add-image" id="pickfiles"> <i class="add-image-ico">+</i> </span>
          </div>
        </div>
      </div>

      <group class="group">
        <selector direction="rtl"
                  placeholder="请选择客户属性"
                  :options="customPropertyOptions"
                  v-model="custom_property"
                  title=" "
                  :class="{'weui-cell_warn': $v.follow.baby_name.$error }"
                  placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>客户属性:</span>
        </selector>
        <cell title="跟进状态">
          <checker v-model="followType"
          default-item-class="ad-checker-item"
          selected-item-class="ad-checker-selected"
          type="radio"
          :max="1"
          :radio-required="true"
          >
            <checker-item value="GH#" class="checker-item-label">关怀</checker-item>
            <checker-item value="DF#" class="checker-item-label">已到访</checker-item>
          </checker>
        </cell>


        <selector direction="rtl"
        placeholder="请选择宝宝"
        :options="babyOpts"
        v-model="babyId"
        title=" "
        :class="{'weui-cell_warn': $v.follow.baby_name.$error }"
        placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>宝宝姓名:</span>
        </selector>

        <selector direction="rtl"
        placeholder="请选择校区"
        :options="campuOpts"
        v-model="campu"
        :class="{'weui-cell_warn':
          $v.follow.intention_team_id &&
          $v.follow.intention_team_id.$error ||
          $v.follow.df_team_id &&
          $v.follow.df_team_id.$error}"

        title=" "
        placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>{{ followType === GH ? '意向校区:' : '已到访校区:' }}</span>
        </selector>

        <x-input
        name="prediction_ratio"
        keyboard="number"
        text-align="right"
        :class="{'weui-cell_warn': $v.follow.prediction_ratio &&
        $v.follow.prediction_ratio.$error }"
        placeholder="请输入预计签约率(%)"
        type="number" v-model="follow.prediction_ratio">
          <span slot="label"><i class="require-mark"></i>预计签约率(%):</span>
        </x-input>

        <x-input
        name="prediction_sum"
        keyboard="number"
        text-align="right"
        :class="{'weui-cell_warn': $v.follow.prediction_sum &&
        $v.follow.prediction_sum.$error }"
        placeholder="请输入预计签约金额"
        :is-type="money" v-model="follow.prediction_sum">
          <span slot="label"><i class="require-mark"></i>预计签约金额:</span>
        </x-input>

        <cell>
          <span slot="title"><i class="require-mark"></i>预计签约时间:</span>
          <datetime
          clear-text="取消时间"
          :startDate="currentDateTime"
          endDate="2040-01-01 00:00"
          @on-clear="follow.prediction_time = ''"
          type="datetime"
          confirmText="完成"
          cancelText="取消"
          title=" "
          :class="{'weui-cell_warn': $v.follow.prediction_time &&
          $v.follow.prediction_time.$error }"
          v-model="prediction_time"
          placeholder="请选择预计签约时间">
          </datetime>
        </cell>


        <cell
          v-if="followType === GH "
          title="是否预约:">
          <checker v-model="isYY"
          @on-change="changeYYType"
          default-item-class="ad-checker-item"
          selected-item-class="ad-checker-selected"
          >
            <checker-item value="YY#" class="checker-item-label">是</checker-item>
            <checker-item value="GH#" class="checker-item-label">否</checker-item>
          </checker>
        </cell>

        <cell title="已到访类型:"
        v-if="followType === DF "
        >
          <checker v-model="dfType"
          default-item-class="ad-checker-item"
          selected-item-class="ad-checker-selected"
          :radio-required="true"
          >
            <checker-item :value="ST" class="checker-item-label">已试听</checker-item>
            <checker-item :value="GM" class="checker-item-label">已观校</checker-item>
          </checker>
        </cell>
      </group>

      <group v-if="isYY === 'YY#' || followType === DF ">
        <cell>
          <span slot="title">
           {{getDescPrefix(dfType)}}时间:
          </span>

          <datetime
          clear-text="取消时间"
          :startDate="currentDateTime"
          endDate="2040-01-01 00:00"
          @on-clear="actual_time = ''"
          type="datetime"
          confirmText="完成"
          cancelText="取消"
          title=" "
          :class="{'weui-cell_warn':
          $v.follow.actual_time &&
          $v.follow.actual_time.$error }"
          v-model="actual_time"
          :placeholder="'请选择'+getDescPrefix(dfType)+'时间'">
          </datetime>
        </cell>

        <selector direction="rtl"
                  v-if="isYY === 'YY#' && followType === GH"
                  title=" "
                  @on-change="changeYuYueType"
                  :options="optYuYuytype"
                  v-model="follow.yy_type_id"
                  placeholder-align="right">
          <span slot="label">预约类型:</span>
        </selector>

        <selector direction="rtl"
        title=" "
        placeholder="请选择课程"
        @on-change="changeCourse"
        :options="courseOpts"
        v-model="follow.course_id"
        :class="{'weui-cell_warn':
        $v.follow.course_id &&
        $v.follow.course_id.$error }"
        placeholder-align="right">
          <span slot="label">
          {{getDescPrefix(dfType)}}课程:</span>
        </selector>

      </group>

      <group>
        <cell>
          <span slot="title">下次提醒时间</span>
          <datetime
          @on-clear="next_time = ''"
          clear-text="取消时间"
          type="datetime"
          :startDate="currentDateTime"
          endDate="2040-01-01 00:00"
          confirmText="完成" cancelText="取消"
          title="下次提醒时间:"
          v-model="next_time"
          placeholder="请选择下次提醒时间">
          </datetime>
        </cell>
      </group>

      <div class="full mgt-15">
      </div>
      <div class="mgt-15 btn-group ">
        <span class="scrm-default-btn small" @click="saveClue">保存</span>
      </div>

      <x-dialog v-model="this.$store.state.app.dialogShow">
        <div class="dialog-message">
          {{ this.$store.state.app.dialogMessage }}
        </div>
        <span class="vux-close" @click="hideDialog">知道了</span>
      </x-dialog>

      <confirm v-model="propConfirm"
               title="温馨提示"
               @on-confirm="setPropConfirm">
        <p style="text-align:center;">当前客户类型为<span style="color: red;">{{ this.custom_property_name }}</span>,确定要保存跟进记录吗？</p>
      </confirm>

    </div>
  </div>
</template>

<script>
  var dateFormat = require('dateformat')
  //  import {XInput, Group, ChinaAddressData, XAddress, Selector, Datetime, Cell} from 'vux';
   import XInput from 'vux/src/components/x-input'
   import Group from 'vux/src/components/group'
   import XAddress from 'vux/src/components/x-address'
   import ChinaAddressData from 'vux/src/datas/china_address.json'
  //  import Selector from 'vux/src/components/selector'
  //  import Datetime from 'vux/src/components/datetime'
   import Cell from 'vux/src/components/cell'
   import XDialog from 'vux/src/components/x-dialog'
   import { Checker, CheckerItem }  from 'vux/src/components/checker'

   import { DatePicker } from 'element-ui'

   import Selector from '../components/selector'
   import Confirm from 'vux/src/components/confirm'

   import { validationMixin } from 'vuelidate'
   import { required, minLength } from 'vuelidate/lib/validators'

   import { mapState, mapActions } from 'vuex'
   import store from '../store'
   import Q from 'q'
   import axios from 'axios'
  //  import {XDialog} from 'vux'
   import {showDialog, hideDialog} from '../lib/dialog'
   import envFuncs from '@/config/base'
let env = envFuncs.getParams()

   const GH = 'GH#'
   const DF = 'DF#'
   const GM = 'GM#'
   const ST = 'ST#'

   export default{
    mixins: [validationMixin],
    data () {
       var d = new Date()
       var month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
       var day = d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate()
       var hours = d.getHours()
       var minutes = d.getMinutes()
       var str = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + minutes

       return {
         GH: GH,
         DF: DF,
         GM: GM,
         ST: ST,
         custom_property: 'YB#',
         custom_property_name: '',
         next_time: '',
         actual_time: '',
         prediction_time: '',
         caseValue: '',
         babyOpts: [],
         babyId: -1,
         indexedBabies: {},
         custom_type: 1,
         followType: 'GH#',
         currentDateTime: str,
         showLocation: false,
         startDate: '',
         campuOpts: [],
         endDate: '',
         isAudtion: true,
         visitType: '',
         contract_money: null,
         deposit: null,
         format: 'YYYY-MM-DD HH:mm',
         disableTime: false,
         courseOpts: [],
         campu: '',
         number: function (value) {
           return {
             valid: /^\d+$/.test(value),
             msg: '必须为数字'
            }
         },
         money: function (value) {
           return {
             valid: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value),
             msg: '金额格式错误'
            }
         },
         defaultImg: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490190406985&di=2b18eab8b5f2575acbd4d8672441ce38&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e1b756613cf032f8754573ad2961.png',
         followWayOptions: [
          {
            key: 'DH#',
            value: '电话跟进',
          },

          {
            key: 'YY#',
            value: '预约跟进',
          },

          {
            key: 'HD#',
            value: '活动跟进'
          },

          {
            key: 'DF#',
            value: '已到访'
          },

          {
            key: 'WX#',
            value: '微信跟进'
          },
         ],
         isYY: "GH#",
         dfType: ST,
         follow:{
            "custom_property": '',
            "custom_id": 1,
            "clue_desc": "",
            "clue_type": "",
            "clue_insert_type": "",
            "location_j": "",
            "location_w": "",
            "clue_location": "",
            "next_time": "",
            "df_team_id": "",
            "baby_name": "",
            "course_name": "",
            "prediction_sum": "",
            "prediction_time": "",
            "df_type": "",
            "course_id": '',
            "is_yy": "",
            "df_type": ST,
            "prediction_ratio": "",
            "intention_team_id": "",
            'contract_money': '',
            "actual_time" : this.$route.query.type === 'GH#' ? str : '',
            "clue_location_desc" : '定位中...',
            "imgs": [],
            "yy_type": '',
            "yy_type_id": ''
         },
         optYuYuytype: [],
         propConfirm: false
       };
    },

    validations () {
      let defaultRules = {
        baby_name: {
          required
        },
        clue_desc: {
          required
        },
      }

      const prediction_rules = {
        prediction_ratio: {
          required
        },
        prediction_sum: {
          required
        },
        prediction_time: {
          required
        }
      }

      if (this.follow.prediction_sum || this.follow.prediction_time || this.follow.prediction_ratio) {
        defaultRules = {
          ...defaultRules,
          ...prediction_rules
        }
      }

      const auditionRules = {
      }
      if (this.followType === GH) {
        const ghRules = {
          intention_team_id: {
            required
          }
        }
        if (this.follow.is_yy === 'YY#') {
           return {
            follow: {
              ...defaultRules,
              ...auditionRules,
              ...ghRules
            }
          }
        } else {
          return {
            follow: {
              ...defaultRules,
              ...ghRules
            }
          }
        }

      } else {
        const dfRules = {
          ...defaultRules,
          df_team_id: {
            required
          },
        }

        if (this.follow.df_type === GM) {
          return {
            follow: {
              ...dfRules
            }
          }
        } else {
          return {
            follow: {
              ...auditionRules,
              ...dfRules
            }
          }
        }
      }
    },
    destroyed () {
      clearTimeout(this.tid2)
      clearTimeout(this.tid)
    },
    watch: {
      contract_money (contract_money) {
        this.follow.contract_money = contract_money
      },
      deposit (deposit) {
        this.follow.deposit = deposit
      },
      location (location) {
        this.follow.clue_location_desc = this.location.clue_location_desc
        this.follow.clue_location = this.location.clue_location
      },
      babyId (babyId) {
        if (this.indexedBabies[babyId]) {
          this.follow.baby_id = babyId
          this.follow.baby_name = this.indexedBabies[babyId].baby_name
        }
      },
      campu () {
        //  if (this.followType === GH) {
          this.follow.intention_team_id = this.campu
        //  } else if (this.followType === DF) {
          this.follow.df_team_id = this.campu
        //  }
      },
      custom_property (value) {
        this.follow.custom_property = value
        const values = this.customPropertyOptions.filter(elem =>
          elem.key === value)

        if (values.length) {
          this.custom_property_name = values[0].value
        }
      },
      followType (value) {
        this.follow.clue_type = value

        if (!value) {
          this.$nextTick(() => {
            this.followType = GH
          })
        }

        if (this.$v.$error === true) {
          this.$v.follow.$reset()
          this.$v.follow.$touch()
        }
      },
      isYY (value) {
        if (value) {
          this.follow = {
            ...this.follow,
            is_yy: value
          }
        } else {
          this.$nextTick(() => {
            this.isYY = this.follow.is_yy
          })
        }
      },
      dfType (value) {
        if (value) {
          this.follow = {
            ...this.follow,
            df_type: value
          }
        } else {
          this.$nextTick(() => {
            this.dfType = this.follow.df_type
          })
        }
      },
      isAudition (value) {
        this.follow.is_yy = value
      },
      caseValue (value) {
        this.follow.clue_desc = value
      },
      actual_time (val) {
       let actualTime = dateFormat(val, 'yyyy-mm-dd HH:MM')
       if (this.startDate && this.startDate > actualTime) {
         showDialog('跟进时间必须要超过时间' + this.startDate)
         this.actual_time = ''
         return
       }
       this.follow.actual_time = actualTime
     },
     next_time (val) {
       let nextTime = dateFormat(val, 'yyyy-mm-dd HH:MM')
       if (this.startDate && this.startDate > nextTime) {
         showDialog('跟进时间必须要超过时间' + this.currentDateTime)
         this.next_time = ''
         return
       }
       this.follow.next_time = nextTime
     },
     prediction_time (val) {
       let nextTime = dateFormat(val, 'yyyy-mm-dd HH:MM')
       if (this.startDate && this.startDate > nextTime) {
         showDialog('预测时间必须要超过时间' + this.currentDateTime)
         this.prediction_time = ''
         return
       }
       this.follow.prediction_time = nextTime
     }
    },
    beforeMount () {
      this.initCampus()
      this.initCourseList()
      this.initClueYuYueType()
    },
    mounted () {
      let query = this.$route.query
      this.custom_type = query.custom_type

      this.custom_property = encodeURIComponent(query.custom_property)
      this.follow.custom_property = query.custom_type
      //  this.followType = query.type
      this.follow.clue_type = this.followType
      this.follow.custom_id = query.id
      this.filterOptions = this.gbfilterOptions

      if (this.followType === 'GH#') {
        this.disableTime = true
      } else if (['YY#', 'DF#'].indexOf(this.followType) > -1) {
        this.startDate = this.currentDateTime
        this.endDate = '2040-01-01 00:00'
      }
      this.initBabyInfo(query.id)
      //  this.initLocation()

      // this.tid2 = setTimeout(() => {
      //   if (!this.follow.clue_location) {
      //     this.showLocation = true
      //     this.follow.clue_location_desc = '定位失败'
          //  showDialog('定位失败!请点击位置图标强制定位，定位功能不可修改位置!')
          //  this.tid = setTimeout(() => {
          //    hideDialog()
          //  }, 6000)
      //   }
      // }, 4000)

      this.callJsApi('biz.navigation.setTitle',{title:'写跟进'});

      let that = this;

      //  that.loadScript(env.MOXIE, function () {
        that.loadScript(env.PUPLOAD_CDN, function () {
          that.loadScript(env.QINIU_CDN,function () {
            that.initQiniuApiCallback();
          });
        });
      //  });
    },

    components:{
      XInput,
      Group,
      ChinaAddressData,
      XAddress,
      Selector,
      Datetime: DatePicker,
      Cell,
      XDialog,
      Checker,
      CheckerItem,
      Confirm
    },

    methods: {
      ...mapActions({
        getBabys: 'getBabys',
        getTeams: 'getTeams',
        getCourseList: 'getCourseList',
        getClueYuYueType: 'getClueYuYueType'
      }),
      setPropConfirm() {
        let that = this
        this.$v.follow.$touch()

        if (this.$v.$error === true) {
          return;
        }

        if (document.querySelector('.weui-cell_warn')) {
          return showDialog('请检查信息是否正确！')
        }

        if (!this.follow.clue_location) {
          if (this.hasCallLocationDialog === false) {
            this.getLocation().then(() => {
              this.saveClue()
            }).catch(() => {
              // showDialog('获取位置失败，请检查您的网路是否存在问题！如排除网络问题，请刷新页面重试!')
              this.saveClue()
            })
            this.hasCallLocationDialog = true
            return
          }
        }

        if (this.saveLock === true) {
          showDialog('提交中，请勿多次点击!')
          return
        }

        this.saveLock = true
        this.$vux.loading.show({
          text: '提交中'
        })
        this.follow.isPc = 1
        store.dispatch('saveClues', this.follow).then((response) => {
          if (response.data.errcode === 0) {
            showDialog('保存线索成功！')
            this.$vux.loading.hide()
            hideDialog()
            if (this.$route.query.back === 'follow-record') {
              this.$router.replace({path: 'follow-record', query: {custom_type: this.custom_type}})
            } else {
              this.$router.back()
            }
            this.saveLock = false
          } else {
            this.$vux.loading.hide()
            showDialog(response.data.errmsg)
            // hideDialog()
            this.saveLock = false
          }
        }).catch(() => {
          showDialog('保存出错，尝试重试一次！如再不能保存，请联系管理员!')
          this.$vux.loading.hide()
          this.saveLock = false
        })
      },
      getDescPrefix (type) {
        let prefix = ''

        if (this.followType === DF) {
          if (type === ST) {
            prefix = '已试听'
          } else if (type === GM) {
            prefix = '已观校'
          }
        } else {
          prefix = '预约'
        }
        return prefix
      },
      loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        if(typeof(callback) != "undefined") {
          if (script.readyState) {
              script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                  script.onreadystatechange = null;
                  callback();
                }
              }
          } else {
            script.onload = function () {
              callback();
            };
          }
        }
        script.src = url;
        document.body.appendChild(script);
      },
      hideDialog: hideDialog,
      changeYYType (value) {},
      saveClue () {
        if (this.custom_property == encodeURIComponent(this.$route.query.custom_property)) {
          this.propConfirm = true
        } else {
          let that = this
          this.$v.follow.$touch()

          if (this.$v.$error === true) {
            return;
          }

          if (document.querySelector('.weui-cell_warn')) {
            return showDialog('请检查信息是否正确！')
          }

          if (!this.follow.clue_location) {
            if (this.hasCallLocationDialog === false) {
              this.getLocation().then(() => {
                this.saveClue()
              }).catch(() => {
                // showDialog('获取位置失败，请检查您的网路是否存在问题！如排除网络问题，请刷新页面重试!')
                this.saveClue()
              })
              this.hasCallLocationDialog = true
              return
            }
          }

          if (this.saveLock === true) {
            showDialog('提交中，请勿多次点击!')
            return
          }

          this.saveLock = true
          this.$vux.loading.show({
            text: '提交中'
          })
          this.follow.isPc = 1
          store.dispatch('saveClues', this.follow).then((response) => {
            if (response.data.errcode === 0) {
              showDialog('保存线索成功！')
              this.$vux.loading.hide()
              hideDialog()
              if (this.$route.query.back === 'follow-record') {
                this.$router.replace({path: 'follow-record', query: {custom_type: this.custom_type}})
              } else {
                this.$router.back()
              }
              this.saveLock = false
            } else {
              this.$vux.loading.hide()
              showDialog(response.data.errmsg)
              // hideDialog()
              this.saveLock = false
            }
          }).catch(() => {
            showDialog('保存出错，尝试重试一次！如再不能保存，请联系管理员!')
            this.$vux.loading.hide()
            this.saveLock = false
          })
        }
      },
      initCampus () {
        this.getTeams({page_size: 1000}).then((response) => {
          if (response.data.errcode === 0) {
            const results = response.data.results
            if (results && results.teams && results.teams.length) {
              const teams = results.teams
              teams.forEach((elem, index) => {
                this.campuOpts.push({
                  key: elem.id,
                  value: elem.team_name
                })
              })

              const myTeamList = this.user.my_team_list
              let defaultTeamId, filteredTeams
              for (const teamId in myTeamList) {
                filteredTeams = teams.filter(elem => elem.id == teamId)
                if (filteredTeams.length) {
                  this.campu = filteredTeams[0].id
                  break
                }
              }
            }
          }
        })
      },
      initCourseList () {
        this.getCourseList().then((response) => {
          if (response.data.errcode === 0) {
            const results = response.data.results
            if (results) {
              Object.values(results).forEach((elem, index) => {
                this.courseOpts.push({
                  key: elem.course_id,
                  value: elem.course_name
                })
              })
            }
          }
        })
      },
      initClueYuYueType () {
        this.getClueYuYueType().then((response) => {
          if (response.data.errcode === 0) {
            const results = response.data.results
            if (results && results.length) {
              Object.values(results).forEach((elem, index) => {
                this.optYuYuytype.push({
                  key: elem.id,
                  value: elem.name
                })
              })
              this.follow.yy_type = results[0].name
              this.follow.yy_type_id = results[0].id
            }
          }
        })
      },
      changeCourse (courseID) {
        const values = this.courseOpts.filter(elem =>
          elem.key === courseID)

        if (values.length) {
          this.follow.course_name = values[0].value
        }
      },
      changeYuYueType (typeID) {
        const values = this.optYuYuytype.filter(elem => elem.key === typeID)
        console.log('yy_type', typeID)
        console.log('yy_type', values)

        if (values.length) {
          this.follow.yy_type = values[0].value
        }
      },
      initBabyInfo (id) {
        return Q.Promise((resolve, reject) => {
          this.getBabys(id)
            .then((response) => {
              if (response.data.errcode === 0) {
                const babyList = response.data.results
                const babyOpts = [{key: -1, value: '请选择宝宝'}]
                if (babyList) {
                  babyList.forEach((baby, index) => {
                    babyOpts.push({key: baby.id, value: baby.baby_name})
                    this.indexedBabies[baby.id] = baby
                  })
                  this.babyOpts = babyOpts
                  const defaultBaby = babyOpts.concat([]).splice(1)
                  if (defaultBaby.length) this.babyId = defaultBaby[0].key
                }
                resolve()
              } else {
                reject()
                console.log('服务器错误！请联系管理员!')
              }
            })
        })
      },
      getClueLocationDesc (response, type) {
        let addr = ''
        if(type === 1) {
          addr = response.snippet + response.title
        } else {
          addr = response.address
        }
        console.log('addr', addr)
        if(addr.length > 10) {
          addr = addr.substr(0, 10) +'...'
        }
        console.log(addr, 'getClueLocationDesc')
        return addr
      },
      initLocationByResponse (response, type) {
        this.follow.clue_location_desc = this.getClueLocationDesc(response, type)
        this.follow.location_j = response.longitude
        this.follow.location_w = response.latitude
        this.location = response
      },
      initLocation () {
        Q.Promise((success, error) => {
          this.callJsApi('device.geolocation.get', {
            targetAccuracy : 2,
            coordinate : 0,
            withReGeocode : true
          }).then((response) => {
            console.debug('初始化位置成功：', JSON.stringify(response))
            this.initLocationByResponse(response)
            this.follow.clue_location = response.address
            console.debug(this, this.clue_location)
            success()
          }).catch((aerror) => {
            console.debug('初始化位置失败：', aerror)
            error(aerror)
          })
        }).catch((cerror) => {
          console.debug(cerror)
        })
      },

      getLocation () {
        console.log('test')
        return Q.Promise((success, error) => {
          this.callJsApi('biz.map.locate')
          .then((response) => {
            console.log('获取位置成功：', JSON.stringify(response))
            // this.initLocationByResponse(response, 1)
            this.follow.clue_location = response.province + response.city + response.snippet
            this.follow.clue_location_desc = this.follow.clue_location
            console.log('this.follow.clue_location', this.follow.clue_location)
            success()
          }).catch((aerror) => {
            error(aerror)
            // console.log('获取位置失败：', aerror)
            // showDialog('获取位置失败, 请刷新页面重试!')
            // success()
          })
        })
      },
      uploadImage () {

        if(this.isQiniuInstalled === true) {

        let uptoken_url = env.CRM_API_HOST+'/users/'+this.token+'/upload_token';
        let that = this;

        try {
          axios.get(uptoken_url).then((response) => {
            console.log(response, 'eee')
            if(response.data.errcode == 0) {
              let uptoken = response.data.results.token;
              let domain = response.data.results.domain;

              console.log('token :', Qiniu, domain, uptoken)
              console.log(document.getElementById('pickfiles'))

              let uploader = Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: 'pickfiles',
                //  container: 'container',
                drop_element: 'container',
                max_file_size: '1000mb',
                flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
                dragdrop: true,
                chunk_size: '1000mb',
                multi_selection: false,
                //  uptoken_url: $('#uptoken_url').val(),
                uptoken:uptoken,
                domain: domain,
                get_new_uptoken: false,
                // downtoken_url: '/downtoken',
                // unique_names: true,
                // save_key: true,
                // x_vars: {
                //   'id': '1234',
                //   'time': function(up, file) {
                //     var time = (new Date()).getTime();
                //     // do something with 'time'
                //     return time;
                //   },
                // },
                auto_start: true,
                log_level: 5,
                init: {
                  'FilesAdded': function(up, files) {
                    //  $('table').show();
                    //  $('#success').hide();
                    //  plupload.each(files, function(file) {
                    //    var progress = new FileProgress(file, 'fsUploadProgress');
                    //    progress.setStatus("ç­‰å¾…...");
                    //    progress.bindUploadCancel(up);
                    //  });
                  },
                  'BeforeUpload': function(up, file) {
                  that.$vux.loading.show({
                    text: 'Loading'
                  })
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                    //  if (up.runtime === 'html5' && chunk_size) {
                    //    progress.setChunkProgess(chunk_size);
                    //  }
                  },
                  'UploadProgress': function(up, file) {
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                    //  progress.setProgress(file.percent + "%", file.speed, chunk_size);
                    console.log(file,1)
                  },
                  'UploadComplete': function(event, files, info) {
                    //  $('#success').show();
                      console.log('success', file, info)
                      let file = files.pop();
                      that.follow.imgs.push({url:domain+'/'+file.name})
                      that.$vux.loading.hide();
                  },
                  'FileUploaded': function(up, file, info) {
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  progress.setComplete(up, info);
                  },
                  'Error': function(up, err, errTip) {
                    //  $('table').show();
                    //  var progress = new FileProgress(err.file, 'fsUploadProgress');
                    //  progress.setError();
                    //  progress.setStatus(errTip);
                  }
                    // ,
                    // 'Key': function(up, file) {
                    //   var key = "";
                    //   // do something with key
                    //   return key
                    // }
                }
              });

              uploader.bind('FileUploaded', function() {
                console.log('hello man,a file is uploaded');
              });

              // domain为七牛空间对应的域名，选择某个空间后，可通过 空间设置->基本设置->域名设置 查看获取
              // uploader为一个plupload对象，继承了所有plupload的方法
              console.log('============初始化qiniu完毕============')
            } else {
              console.log('初始化qiniu出错!', JSON.stringify(response.data))
            }
          }).catch( (errcode) => {
            console.log(errcode)
          })

        } catch(e) {
          console.log(e)
        }

        // let response = {
        //   "errcode": 0,
        //   "errmsg": "接口调用成功!",
        //   "results": {
        //   "token": "6EZmwsqQYeHvlaA44_LwiBAePez-rjpOv4jwg4t4:cYU1nbpCi9jzuejkwhstLZ9wWeQ=:eyJzY29wZSI6Im1xY3JtIiwiZGVhZGxpbmUiOjE0OTA3MjEwNjEsInVwSG9zdHMiOlsiaHR0cDpcL1wvdXAucWluaXUuY29tIiwiaHR0cDpcL1wvdXBsb2FkLnFpbml1LmNvbSIsIi1IIHVwLnFpbml1LmNvbSBodHRwOlwvXC8xODMuMTM2LjEzOS4xNiJdfQ==",
        //   "domain": "http://ocuvbzm86.bkt.clouddn.com"
        //   }
        // }
        }

      },

      deleteImage (img) {
        let index = -1
        if(index = this.follow.imgs.indexOf(img) > -1) {
          if(this.follow.imgs.length>1) {
            this.follow.imgs.splice(index, 1)
          } else {
            this.follow.imgs.pop()
          }
        }
      },

      initQiniuApiCallback () {
        this.isQiniuInstalled = true;
        this.uploadImage();
      }
    },
    destroyed () {
      if (this.sid) clearTimeout(this.sid)
    },
    computed: {
      customPropertyOptions () {
        return this.$store.state.app.customPropertyOptions
      },
      ...mapState({
        token: state => state.app.token,
        user: state => state.app.user,
        location: state => state.app.location
      })
    }
 }
</script>

<style lang="less">
  @import "../less/base.less";

  @add-plus-size:40px;

  @add-plus-color: rgb(76, 169, 229);

  .container{
    padding-bottom: 300px;
    .full{
      height: 10px;
    }
  }

  .add-follow-main{

      .checker-item-label {
        border: 1px solid #cccccc;
        padding: 0 16px;
        border-radius: 4px;
        font-size: 14px;
      }

      .ad-checker-selected.checker-item-label {
        border: 1px solid #4ca9e5;
        color: #4ca9e5;
      }

      .checker-item-label.case-item {
        border-radius: 20px;
        color: #cccccc;
      }

      .ad-checker-selected.case-item {
        border: 1px solid #cccccc;;
        color: #cccccc;
      }

      .case-wrapper {
        margin: 10px 0;
        padding: 0 6px;
      }

      .add-plus{
        display: inline-block;
        border: 1px solid @add-plus-color;
        width: @add-plus-size;
        height: @add-plus-size;
        line-height: @add-plus-size*.9;
        text-align: center;
        border-radius: 50%;
        font-size: 1.8em;
        font-weight: 20px;
        color: @add-plus-color;
      }

      .btn-group{
        margin-top: 100px;

        &>*{
        }
      }


      .textarea-wrapper{
        background-color: white;
        &:extend(.clearfix all);
        overflow: hidden;

        .txtare-block {
          padding: 6px;
          margin-bottom: 10px;
        }

        textarea {
          display: block;
          border:none;
          width: 100%;
          font-size: 16px;
          height: 8rem;
          padding: 8px 0 0;
          text-indent: 8px;
          border: 1px solid #e4e4e4;
        }

        textarea::placeholder {
          color: #cccccc;
        }
      }

      .location-ico{
        background: url("@{host}/location_ico.svg") no-repeat 0 0;
        width: 20px;
        height: 24px;
        display: inline-block;
        margin-right: 4px;
        vertical-align: middle;
      }
      .location-addr {
        vertical-align: middle;

      }

      .image-contr {
        &:extend(.clearfix all);
        padding-bottom: 14px;
      }

      @image-item-size : 100px;

      .image-item{
        width: @image-item-size;
        height: @image-item-size;
        float: left;
        margin: 5px 5px;
        position: relative;
      }

      .image-item:not(.previewed-image) {
        box-shadow: 2px 2px 10px rgba(100,100,100,0.8), 0 0 10px rgba(233,233,233,0.8);
      }

      .previewed-image {
        position: relative;
      }

      .delete {
        width: 10px;
        height: 10px;
        line-height: 11px;
        border: 1px solid #4ca9e5;
        background-color: #4ca9e5;
        border-radius: 50%;
        position: absolute;
        right:-6px;
        top:-6px;
        font-style: normal;
        text-align: center;
        color: white;
        padding: 4px;
        font-size: 12px;
      }

      .add-image {
        border: 1px solid #4ca9e5;
        color: #4ca9e5;
        display: block;
        border-radius: @image-item-size;
        font-size: 2em;
        height: @image-item-size;
        line-height: @image-item-size;
        text-align: center;
        font-weight: bolder;
        overflow: hidden;
      }

      .add-image-ico {
        font-style: normal;
      }

      .image-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .clue-locaton-desc {
        padding: 0px 10px;
        margin: 2px 0;
        color: #cccccc;
      }

      .location-ico {

      }
  }
</style>
